package com.story.framework.core.utils.Hot100.java;


/**
 * @Author: Xiaohei
 * @CreateTime: 2022/2/14 22:21
 */
public class AddTwoNumbers {

    public static void main(String[] args) {
        ListNode l13 = new ListNode(9);
        ListNode l12 = new ListNode(9, l13);
        ListNode l11 = new ListNode(9, l12);
        ListNode l1 = new ListNode(9, l11);

        ListNode l22 = new ListNode(9);
        ListNode l21 = new ListNode(9, l22);
        ListNode l2 = new ListNode(9, l21);

        ListNode node = addTwoNumbers(l1, l2);
        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }
    }

    /**
     * 递归解决？No
     * 执行用时：1 ms, 在所有 Java 提交中击败了100.00%的用户
     * 内存消耗：41.6 MB, 在所有 Java 提交中击败了5.08%的用户
     * @param l1 l1
     * @param l2 l2
     * @return sum
     */
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        ListNode head = l1;
        int up = 0;
        ListNode t1 = l1;
        while (l1 != null && l2 != null) {
            l1.val += l2.val;
            if (up == 1) {
                l1.val++;
                up = 0;
            }
            if (l1.val >= 10) {
                up = 1;
                l1.val = l1.val % 10;
            }
            t1 = l1;
            l1 = l1.next;
            l2 = l2.next;
        }

        if (l1 == null) {
            t1.next = l2;
            l1 = t1.next;
            if (l1 == null) {
                if (up==1) {
                    t1.next = new ListNode(1);
                }
                return head;
            }
        }
        while (l1.next != null) {
            if (up == 1) {
                l1.val++;
                up = 0;
            }
            if (l1.val >= 10) {
                l1.val = l1.val % 10;
                up = 1;
                l1 = l1.next;
            }else {
                break;
            }
        }
        if (l1.next == null && up == 1) {
            l1.val++;
            if (l1.val >= 10) {
                l1.val = l1.val % 10;
                l1.next = new ListNode(1);
            }
        }
        return head;
    }
}
